/*
 * CameraGround.cpp
 *
 *  Created on: 25/10/2012
 *      Author: Matias_2
 */
#include "cameras/CameraGround.h"
#include <GL/glew.h>
#include <iostream>  // FIXME delete include

CameraGround::CameraGround() {
	position = glm::vec3(GROUND_INIT_X, GROUND_INIT_Y, GROUND_INIT_Z);
	angle = 0;
	rotationX = 0;
	rotationY = 0;
	antRotationX = 0;
	antRotationY = 0;
}

CameraGround::~CameraGround() { }

glm::mat4 CameraGround::getViewMatrix() {
	glm::mat4 transformation = glm::mat4 (1.0f);
	transformation = glm::lookAt(position, glm::vec3(position.x, position.y + 2, position.z), glm::vec3(0,0,1));
	transformation = glm::translate(transformation, glm::vec3(position.x, position.y, position.z));
	transformation = glm::rotate(transformation, -rotationY, glm::vec3(1.0f, 0.0f, 0.0f));
	transformation = glm::rotate(transformation, -rotationX, glm::vec3(0.0f, 0.0f, 1.0f));
	transformation = glm::translate(transformation, glm::vec3(-position.x, -position.y, -position.z));
	return transformation;
}

void CameraGround::OnMouseMove(int x, int y) {
	GLint viewport[4];
	glGetIntegerv(GL_VIEWPORT, viewport);

	rotationX += ((viewport[2]/2 -  x) * GROUND_SPEED_ROTATION);
	rotationX -= antRotationX;
	antRotationX = rotationX;
	if (rotationX > GROUND_MAX_ROTATION_X)
		rotationX -= GROUND_MAX_ROTATION_X;
	if (rotationX < -GROUND_MAX_ROTATION_X)
		rotationX += GROUND_MAX_ROTATION_X;

	rotationY += ((viewport[3]/2 - y) * GROUND_SPEED_ROTATION);
	rotationY -= antRotationY;
	antRotationY = rotationY;
	if (rotationY > GROUND_MAX_ROTATION_Y)
		rotationY = GROUND_MAX_ROTATION_Y;
	if (rotationY < 0)
		rotationY = 0;
}

void CameraGround::OnKeyDown(int nKey, char cAscii) {
	if (cAscii == 'a') {
		position.x -= cos(-rotationX * PI / 180) * GROUND_SPEED_WALK;
		position.y += sin(-rotationX * PI / 180) * GROUND_SPEED_WALK;
	} else if (cAscii == 's') {
		position.x -= sin(-rotationX * PI / 180) * GROUND_SPEED_WALK;
		position.y -= cos(-rotationX * PI / 180) * GROUND_SPEED_WALK;
	} else if (cAscii == 'd') {
		position.x += cos(-rotationX * PI / 180) * GROUND_SPEED_WALK;
		position.y -= sin(-rotationX * PI / 180) * GROUND_SPEED_WALK;
	} else if (cAscii == 'w') {
		position.x += sin(-rotationX * PI / 180) * GROUND_SPEED_WALK;
		position.y += cos(-rotationX * PI / 180) * GROUND_SPEED_WALK;
	}
}

void CameraGround::registerListener() {
	InputMgr::getInstance()->registerListener((KeyListener*) this);
	InputMgr::getInstance()->registerListener((MouseListener*) this);
}

void CameraGround::deleteListener() {
	InputMgr::getInstance()->deleteListener((KeyListener*) this);
	InputMgr::getInstance()->deleteListener((MouseListener*) this);
}
